/*
 * @Author       : xiangmin
 * @File         : 空态自定义指令
 * @Date         : 2023-06-23 11:22:24
 * @LastEditors  : xiangmin
 * @LastEditTime : 2023-08-05 14:06:45
 */

import CEmpty from '@/components/CEmpty.vue'
import { needSetPosition } from '@/utils'
import { h, render, type ObjectDirective } from 'vue'

function appendEmpty(element: HTMLElement) {
	if (needSetPosition(window.getComputedStyle(element).position) && needSetPosition(element.style.position)) {
		element.style.position = 'relative'
	}
	const wrap = document.createElement('div')
	wrap.id = 'v-empty'
	const props = {
		description: element.getAttribute('empty-text') || '哎呀，木有数据~',
		icon: element.getAttribute('empty-icon') || 'empty',
		size: element.getAttribute('empty-size') || '200'
	}
	const image = element.getAttribute('empty-image')
	// @ts-ignore
	if (image) props.image = image
	const vnode: VNode = h(CEmpty, props)
	render(vnode, wrap)
	element.appendChild(wrap)
}

function removeEmpty(element: HTMLElement) {
	const wrap = element.querySelector('#v-empty')
	wrap && element.removeChild(wrap)
}

const empty: ObjectDirective<HTMLElement, boolean> = {
	mounted(element, binding) {
		if (binding.value) {
			appendEmpty(element)
		}
	},

	updated(element, binding) {
		if (binding.value !== binding.oldValue) {
			binding.value && appendEmpty(element)
			!binding.value && removeEmpty(element)
		}
	}
}

export default empty
